package com.sunday.common.core.remoting.rest.page;

import com.sunday.common.core.converter.MapperConvert;
import com.sunday.common.core.remoting.base.page.BasePage;
import com.sunday.common.core.remoting.base.page.PageResultDTO;
import com.sunday.common.core.utils.ReflectToJsonUtils;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Collections;
import java.util.Optional;

/**
 * 查询分页实体 VO
 *
 * @author zsy
 * @since 2022/10/14
 */
@Data
@NoArgsConstructor
public class PageVO<T> extends BasePage<T> {

    static {
        MapperConvert.getFactory().classMap(PageResultDTO.class, PageVO.class)
                .exclude("records")
                .byDefault()
                .register();
    }

    /**
     * 分页构造函数
     *
     * @param current  当前页
     * @param pageSize 每页显示条数
     * @return {@link null}
     */
    public PageVO(long current, long pageSize) {
        super(current, pageSize);
    }

    public PageVO(long current, long pageSize, long total) {
        super(current, pageSize, total);
    }

    /* --------------- 以下为静态构造方式 --------------- */
    public static <T> PageVO<T> of(long current, long pageSize) {
        return of(current, pageSize, 0);
    }

    public static <T> PageVO<T> of(long current, long pageSize, long total) {
        return new PageVO<T>(current, pageSize, total);
    }

    /**
     * 获取页面信息，返回VO渲染对象
     *
     * @param pageResultDTO
     * @param recordsType
     * @return {@link com.sunday.common.core.remoting.rest.page.PageVO<T>}
     */
    public static <T> PageVO<T> of(PageResultDTO<?> pageResultDTO, Class<T> recordsType) {
        PageVO<T> target = MapperConvert.map(pageResultDTO, PageVO.class);
        target.setRecords(Optional.ofNullable(pageResultDTO.getRecords())
                .map(data -> data.stream()
                        .map(o -> MapperConvert.map(o, recordsType))
                        .toList()
                )
                .orElse(Collections.emptyList()));
        return target;
    }

    @Override
    public String toString() {
        return ReflectToJsonUtils.toJson(this);
    }
}
